import axios from 'axios'
import qs from 'qs'

// 项目可能存在多个服务器
const defaultServer = 'java'
const baseURL = {java: '/api'}
const okCode = 200

// 设置默认的超时请求时间10秒
axios.defaults.timeout = 10000
// 设置CORS跨域请求允许携带资源凭证
axios.defaults.withCredentials = true
// 设置请求拦截器,用于在请求头中添加token
axios.interceptors.request.use(config => {
  const token = 'token_used_for_testing'
  if (token) {
    config.headers.token = token
  }
  return config
}, error => Promise.reject(error))
// 自定义成功的状态码: 2XX 和 3XX (注：默认只有2XX代表成功)
axios.defaults.validateStatus = status => /^([2|3])\d{2}$/.test(status.toString())
// 设置响应拦截器,统一处理响应结果
axios.interceptors.response.use(response => {
  // 如果response.data的结构是{code:__,msg:__,data:__,...},
  // 则将response.data上的属性都挂载到response对象上
  if (response.data && 'code' in response.data && 'msg' in response.data && 'data' in response.data) {
    const resp = response.data
    for (const key in resp) {
      response[key] = resp[key]
    }
    if (resp.code === okCode) {
      response['ok'] = true
    } else {
      response['ok'] = false
      // 分析返回的业务状态码
      switch (resp.code) {
      case 400:
        console.log(`错误码400->${resp.msg}->${resp.data}`)
        break
      case 500:
        console.log(`错误码500->${resp.msg}->${resp.data}`)
        break
      case 501:
        console.log(`错误码501->${resp.msg}->${resp.data}`)
        break
      default:
        console.log(`未知错误:${resp.code}->${resp.msg}`)
        break
      }
    }
  }
  return response
}, error => {
  const {response} = error
  if (response) {
    // 分析返回的系统状态码, 此时服务器返回了结果，但状态码不是2XX或3XX
    switch (response.status) {
    case 401:
      // 没有权限，一般指未登陆
      console.log('未登陆')
      break
    case 403:
      // 一般是token过期
      console.log('token验证失败,服务器拒绝执行')
      break
    case 404:
      console.log('当前请求的接口不存在')
      break
    default:
      console.log('错误码', response.status)
      break
    }
  } else {
    // 服务器没有返回结果
    if (!window.navigator.onLine) {
      // 如果发生断网
      console.log('网络连接已断开')
      return
    }
    return Promise.reject(error)
  }
})

function buildURL(originalURL = '', server = defaultServer) {
  if (originalURL.startsWith('http')) {
    return originalURL
  } else {
    return baseURL[server] + originalURL
  }
}

// 表单方式提交POST请求
function post(url = '', data = {}, headers = {}, server = defaultServer) {
  return axios.post(buildURL(url, server), data, {
    transformRequest: data => qs.stringify(data),
    headers: Object.assign({'Content-Type': 'application/x-www-form-urlencoded'}, headers)
  })
}

// JSON方式提交POST请求
function postJson(url = '', data = {}, headers = {}, server = defaultServer) {
  return axios.post(buildURL(url, server), data, {
    headers: Object.assign({'Content-Type': 'application/json'}, headers)
  })
}

function get(url = '', data = {}, headers = {}, server = defaultServer) {
  return axios.get(buildURL(url, server), {params: data, headers})
}

function del(url = '', data = {}, headers = {}, server = defaultServer) {
  return axios.delete(buildURL(url, server), {data, headers})
}

function patchJson(url = '', data = {}, headers = {}, server = defaultServer) {
  return axios.patch(buildURL(url, server), data, {
    headers: Object.assign({'Content-Type': 'application/json'}, headers)
  })
}

function putJson(url = '', data = {}, headers = {}, server = defaultServer) {
  return axios.put(buildURL(url, server), data, {
    headers: Object.assign({'Content-Type': 'application/json'}, headers)
  })
}

export {post, postJson, get, del, patchJson, putJson, baseURL}
export default axios
